#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
import os
def cut_node( node ):
    #NODE_VXXX_IXXX_CXXXX_SXXX
    tempArray = []
    if node.find( "NODE_V" ) == -1:
        return []

    tempArray = node.strip().split('_')
    if len(tempArray) != 5:
        return []

    if tempArray[0] != "NODE":
        return []


    if ( len( tempArray[1] ) != 4 ) or ( tempArray[1][0] != 'V' ):
        return []

    if ( len( tempArray[2] ) != 4 ) or ( tempArray[2][0] != 'I' ):
        return []

    if ( len( tempArray[3] ) != 5 ) or ( tempArray[3][0] != 'C' ):
        return []
    
    if ( len( tempArray[4] ) != 4 ) or ( tempArray[4][0] != 'S' ):
        return []

    return [ x[1:] for x in tempArray if x != "NODE" ]


def chooseNode( curWifiNode = "" ):
    #fWifiNodeInfo = os.popen("iwlist scan")
    curNodeArray = cut_node(curWifiNode)
    fWifiNodeInfo = open("temp" , "r")
    wifiNodeInfo = fWifiNodeInfo.read()
    fWifiNodeInfo.close()
    tempArray = wifiNodeInfo.splitlines()
    wifiNodeDiv = []
    for line in tempArray:
        if line.find("Cell") != -1:
            tempMac = line.strip().split("Address: ")[1].strip()
        if line.find("Channel:") != -1:
            tempChannel = line.strip().split("Channel:")[1].strip()
        if line.find("Quality=") != -1:
            tempQa = line.strip().split("Quality=")[1].strip().split("/70")[0].strip()
        if line.find("ESSID:") != -1:
            tempESSID = line.strip().split("ESSID:")[1].strip('"')
            tempArray = cut_node(tempESSID)
            if tempArray:
                wifiNodeDiv.append( [ tempESSID , tempMac , tempQa , tempChannel ,  tempArray ] )

    if not wifiNodeDiv:
        print "wifiNodeDiv is null"
        return ""

    wifiNodeDiv = sorted(wifiNodeDiv , key = lambda x : [ x[4][0] , x[4][1] ] ,reverse = True )
    

    if curWifiNode and wifiNodeDiv[0][4][0] <= curNodeArray[0]:
        tempArray = [ x for x in wifiNodeDiv if x[4][3] <= curNodeArray[3] ]
        if not tempArray:
            print "tempArray is null"
            return ""
        tempArray = sorted( tempArray , key = lambda x : x[4][3] , reverse = True )
        return tempArray[0][0]
    else:
        return wifiNodeDiv[0][0]


if __name__ == "__main__":
    print chooseNode()
    print cut_node("NODE_V100_I999_C0987_S900")
